<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.bpmBizTitle"
                    placeholder="请输入标题"
                    :max-length="255"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input :disabled="formDisabled" v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    :disabled="formDisabled"
                    :multi="false"
                    v-model="model.proposer"
                    disabled></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart :disabled="formDisabled" v-model="model.proposerDeptId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="关联项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <a-input
                    v-if="formDisabled"
                    readOnly
                    @click.prevent="goProjectDetail(model)"
                    v-model="model.projectName"
                    style="color: #1890FF; cursor: pointer;"
                    placeholder="请选择项目"></a-input>
                  <select-project-input v-else v-model="model.projectId" placeholder="请输入选择项目" :disabled="formDisabled" @input="selectProject"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="manageTeamId">
                  <select-team-input
                    v-model="model.manageTeamId"
                    :tdlx="3"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="关联生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="produceTeamId">
                  <j-dict-select-tag
                    :disabled="formDisabled || !model.projectId"
                    type="list"
                    v-model="model.produceTeamId"
                    :dictCode="produceTeamId"
                    placeholder="请选择生产团队"
                    @input="selectProduceTeamId"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目合同总额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractTotalAmount">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractTotalAmount"
                    placeholder="请输入项目合同总额"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="已回款金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="returnedAmount">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.returnedAmount"
                    placeholder="请输入已回款金额"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同占比（%）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractRate">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractRate"
                    placeholder="请输入合同占比"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同占比金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractRateAmount">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.contractRateAmount"
                    placeholder="请输入合同占比金额"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="已切割金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cutAmount">
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.cutAmount"
                    placeholder="请输入已切割金额"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="本次切割金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentCutAmount">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.currentCutAmount"
                    placeholder="请输入本次切割金额"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" v-model="model.remark" rows="4" placeholder="请输入备注" :max-length="500"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
                  <j-upload :disabled="formDisabled" v-model="model.attachment"></j-upload>
                </a-form-model-item>
              </a-col>
              <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <!-- 项目详情开始 -->
    <erp-project-report-modal ref="projectReport"></erp-project-report-modal>
    <!-- 项目详情结束 -->
    <ErpFinanceTeamCutBillFormPrint v-if="formBpm" class="print_style" id="teamCutBillContent" :formData="model" :formDataHistory="formData"></ErpFinanceTeamCutBillFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import { Decimal } from 'decimal.js'
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import Print from '@/utils/print/printarea.js';
  import ErpFinanceTeamCutBillFormPrint from './ErpFinanceTeamCutBillFormPrint' // 打印
  export default {
    name: 'ErpFinanceTeamCutBillForm',
    components: {
      SelectTeamInput,
      SelectProjectInput,
      SelectUserByDep,
      CommonFlowList,
      ErpFinanceTeamCutBillFormPrint,
      ErpProjectReportModal: () => import('@/views/erp/report/project/modules/ErpProjectReportModal')
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        activeKey: ['1', '2'],
        model: {
         },
        produceTeamId: "erp_omc_team_manager,alias_name,id,audit_status='2'",
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
        projectId: [
            { required: true, message: '请输入关联项目!' }
        ],
        produceTeamId: [
            { required: true, message: '请输入关联生产团队!' }
        ],
        currentCutAmount: [
            { required: true, message: '请输入本次切割金额!' },
            { pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        ]

        },
        url: {
          queryProjectReportById: '/api/erp/project/report/erpProjectReport/queryById',
          queryProjectTask: '/api/erp/omc/project/erpOmcProjectTask/list',
          queryContractManagerFinal: '/api/erp/omc/contractmanager/erpOmcContractManagerFinal/list',
          getBillNo: '/api/erp/finance/team/erpFinanceTeamCutBill/getBillNo',
          getTeamCutAmount: '/api/erp/finance/team/erpFinanceTeamCutBill/getTeamCutAmount',
          add: '/api/erp/finance/team/erpFinanceTeamCutBill/add',
          edit: '/api/erp/finance/team/erpFinanceTeamCutBill/edit',
          queryById: '/api/erp/finance/team/erpFinanceTeamCutBill/queryById'
        }
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      goProjectDetail(record) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryProjectReportById, { id: record.projectId }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectReport.getDetail(model);
              that.$refs.projectReport.title = '项目一览表';
            }
          })
        })
      },
      selectProject(data) {
        if (data.choseObj.length > 0) {
          this.$set(this.model, 'manageTeamId', data.choseObj[0].teamName);
          if (this.model.produceTeamId) {
            this.$set(this.model, 'cutAmount', 0);
            this.$set(this.model, 'produceTeamId', null);
            this.$set(this.model, 'contractRate', 0);
            this.$set(this.model, 'contractRateAmount', 0);
          }
          // 查找对应项目的收款合同
          getAction(this.url.queryContractManagerFinal, { xmmc: data.choseObj[0].id, htlx: 1 }).then((res) => {
            if (res.success) {
              let results = res.result.records || res.result
              if (results.length > 0) {
                this.$set(this.model, 'contractTotalAmount', results[0].bchte);
                this.$set(this.model, 'returnedAmount', results[0].realCollectionPaymentMoney);
              } else {
                this.$set(this.model, 'contractTotalAmount', 0);
                this.$set(this.model, 'returnedAmount', 0);
              }
            }
          })
        // 找到对应项目的生产团队
          getAction(this.url.queryProjectTask, { projectId: data.choseObj[0].id }).then((res) => {
            if (res.success) {
              let results = res.result.records || res.result
              if (results.length > 0) {
                // fix: 过滤productTeam没有值的情况
                let idList = results.filter(value => value.productTeam).map(item => item.productTeam);
                let idRes = idList.join('&');
                if (idRes != null && idRes != '') {
                  this.produceTeamId = 'erp_omc_team_manager,alias_name,id,audit_status=2 and id in (' + idRes + ')';
                } else {
                  this.produceTeamId = 'null';
                }
              } else {
                this.produceTeamId = 'null';
              }
            }
          })
        } else {
          this.produceTeamId = 'null';
          this.$set(this.model, 'manageTeamId', null);
          this.$set(this.model, 'contractTotalAmount', 0);
          this.$set(this.model, 'returnedAmount', 0);
          this.$set(this.model, 'contractRate', 0);
          this.$set(this.model, 'contractRateAmount', 0);
          this.$set(this.model, 'cutAmount', 0);
          this.$set(this.model, 'produceTeamId', null);
        }
      },
      // 选择生产团队
      selectProduceTeamId(data) {
        if (data) {
          getAction(this.url.queryProjectTask, { projectId: this.model.projectId, productTeam: data }).then((res) => {
            if (res.success) {
              let results = res.result.records || res.result
              if (results.length > 0) {
                let contractRate = 0;
                let contractTotalAmount = this.model.contractTotalAmount;
                results.forEach(element => {
                  contractRate += element.contractRate;
                });
                this.$set(this.model, 'contractRate', contractRate);
                this.$set(this.model, 'contractRateAmount', contractTotalAmount * contractRate * 0.01);
              }
            }
          });
          getAction(this.url.getTeamCutAmount, { projectId: this.model.projectId, produceTeamId: data }).then((res) => {
            if (res.success) {
              let results = res.result.records || res.result
              this.$set(this.model, 'cutAmount', results);
            }
          })
        }
      },
      ...mapGetters(['userInfo']),
      // 获取编号
      getBillNo() {
        let that = this;
        getAction(this.url.getBillNo, {}).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'billNo', data);
            this.$set(this.model, 'bpmBizTitle', this.userInfo().employee.name + '-' + data);
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
        this.getBillNo();
        this.model.proposer = this.userInfo().empId;
        this.model.proposerDeptId = this.userInfo().deptId;
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        if (this.model.id) {
          getAction(this.url.queryProjectTask, { projectId: this.model.projectId }).then((res) => {
            if (res.success) {
              let results = res.result.records || res.result
              if (results.length > 0) {
                let idList = results.map(item => item.productTeam);
                let idRes = idList.join('&');
                if (idRes != null && idRes != '') {
                  this.produceTeamId = 'erp_omc_team_manager,alias_name,id,audit_status=2 and id in (' + idRes + ')';
                } else {
                  this.produceTeamId = 'null';
                }
              } else {
                this.produceTeamId = 'null';
              }
            }
          })
        }

        // 加载关联的项目
        if (this.formDisabled && this.model.projectId) {
          getAction(this.url.queryProjectReportById, { id: this.model.projectId }).then(res => {
              this.$set(this.model, 'projectName', res.result.projectName);
          }).catch(e => {
            console.log(e)
          })
        }
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#teamCutBillContent',
          popTitle: '团队切割单详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
<style lang="less" scoped>
.print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
